import { showToast } from './toast'
import { base64ToTempFilePath } from './imageutil'
/**
 * 图片旋转方法
 * @param {string} src - 图片地址
 * @param {number} edg - 旋转角度
 * @param {function} callback - 回调函数
 */
export const rotateAndCropImage = (src, edg, callback) => {
    console.log('---------src',src)
    if (edg % 90 !== 0) {
      throw new Error("旋转角度必须是90的倍数!");
    }
    if (edg === 0) {
      callback({ tempFilePath: src });
      return;
    }
    const canvas = uni.createOffscreenCanvas({
      type: "2d",
    });
    const ctx = canvas.getContext("2d");
    const image = canvas.createImage();
    image.crossOrigin = "anonymous";
    image.src = src;
    image.onload = () => {
      const imgW = image.width;
      const imgH = image.height;
      if (imgW > 4096) {
        showToast("图片宽度不能超过4096");
        return;
      }
      const quadrant = (((edg / 90) % 4) + 4) % 4;
      let rotatedWidth, rotatedHeight;
      switch (quadrant) {
        case 0:
        case 2:
          rotatedWidth = imgW;
          rotatedHeight = imgH;
          break;
        case 1:
        case 3:
          rotatedWidth = imgH;
          rotatedHeight = imgW;
          break;
      }
      canvas.width = rotatedWidth;
      canvas.height = rotatedHeight;
      ctx.translate(canvas.width / 2, canvas.height / 2);
      ctx.rotate((edg * Math.PI) / 180);
      ctx.drawImage(image, -imgW / 2, -imgH / 2, imgW, imgH);
      base64ToTempFilePath(canvas.toDataURL()).then((res) => {
        callback(res);
      });
    };
  };
